package com.pandora.common.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

/**
 * HMACSHA1加密算法工具
 * 
 * @author JingChenglong 2017/12/27 22:22
 *
 */
public class HMACSHA1Utils {

	private static final String ALGORITHM = "HmacSHA1";

	/**
	 * 将给定字符串内容进行HMACSHA1加密
	 * 
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws IllegalStateException
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeyException
	 */
	public static String HMACSHA1(String data, String key, String charset)
			throws IllegalStateException, UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {

		return StringUtils.nullToStrTrim(Base64.encode(signature(data, key, charset)));
	}

	/**
	 * 加密
	 * 
	 * @param data
	 * @param key
	 * @param charset
	 * @return
	 * @throws IllegalStateException
	 * @throws InvalidKeyException
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchAlgorithmException
	 */
	// TODO 研究此方法
	public static byte[] signature(String data, String key, String charset)
			throws IllegalStateException, InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException {

		SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(charset), ALGORITHM);
		Mac mac = Mac.getInstance(ALGORITHM);
		mac.init(signingKey);

		return mac.doFinal(data.getBytes(charset));
	}
}